﻿
using Db7.Collections;
using System.Html;
using System;
namespace Db7
{
    public class VInput : VirtualElement
    {
        public VInput()
        {
            Tag = "input";
            GetSetStringAttribute typGetSet = new GetSetStringAttribute();
            typGetSet.Get = delegate()
            {
                return this.Type;
            };
            typGetSet.Set = delegate(string s)
            {
                this.Type = s;
            };
            this.AttributesNN.ReservedPropertiesNN["type"] = typGetSet;
            GetSetStringAttribute valGetSet = new GetSetStringAttribute();
            valGetSet.Get = delegate()
            {
                if (Value != null)
                {
                    return Value;
                }
                return Value_D;
            };
            valGetSet.Set = delegate(string val)
            {
                if (Value_DB != null)
                {
                    Value_DB.Value = val;
                }
                else
                {
                    Value = val;
                }
            };
            this.Attributes.ReservedProperties["value"] = valGetSet;
        }

        public string Type;

        public string Value;

        public StringBinder Value_DB;

        public string Value_D
        {
            get { return StringBinder.Get(Value_DB); }
            set { 
                Value_DB = StringBinder.Set(Value_DB, value);
                //ElementAttribute ea = this.PhysicalElement.Attributes.GetNamedItem("value");

                Util.SetAttribute(this.PhysicalElement, "value", value);
                //this.PhysicalElement.SetAttribute("value", value);
            }
        }

        public override void DoDefaultRender(RenderContext rcIn, VirtualElement ve)
        {
            base.DoDefaultRender(rcIn, ve);
            if (Value_DB != null)
            {
                RenderContext.RegisterOnChangeHandler(this, OnChange);
                Value_DB.AddOnUpdateNotification(SetValueToItself);  
            }
        }

        private void SetValueToItself()
        {
            
            this.Value_D = this.Value_D;
        }

        private void OnChange(ElementEvent e)
        {
            InputElement input = e.SrcElement.As<InputElement>();
            Value_DB.Value = input.Value;
        }
    }
}
